# -*- coding:utf-8 -*-

from flask import request, render_template, jsonify, session, g
from app.models.application import Advice, Tracking
from app import db
from flask_login import login_required
import datetime
from sqlalchemy.sql import or_
from app.tools.permission import permission
from app.tools.log import log
from app.tools.safe import safe_data
from . import advice


@advice.before_request
@login_required
@permission(['service', 'director', 'admin', 'super'])
def check_permission():
	g.kw = {}
	if session.get('role') == 'service':
		g.kw['tracker_id'] = session.get('sid')	#客服只能看到分配给自己的单，其他角色可以看到全部
	return

@advice.route('/list/')
def advice_list():	#返回投诉建议的列表页面，相关数据由ajax异步获取
	return render_template('tracking/advice/list.html', title=u'投诉建议')

@advice.route('/get_list/')
def get_list():	#获取投诉建议的数据
	values = request.values
	limit = int(values.get('limit', '10'))
	offset = int(values.get('offset', '0'))
	list_type = values.get('list_type')
	number = values.get('number')
	start = values.get('start')
	end = values.get('end')
	submitter = values.get('submitter')
	area = values.get('area')
	search_type = values.get('search_type')
	tb_name = values.get('tb_name')	#前端页面中多个表格共用同一组搜索参数，tb_name用于标识当前是哪一个表格在使用这些参数
	if list_type is None:
		return jsonify({'state': -1, 'msg': u'参数不全'})
	try:
		start = datetime.datetime.strptime(start, '%Y-%m-%d')
		end = datetime.datetime.strptime(end, '%Y-%m-%d')
		end = end + datetime.timedelta(days=1)	#需要加一天才可以搜索到原本的end指定的日期
	except ValueError:
		return jsonify({'state': 1, 'msg': u'参数错误'})
	result = Advice.query
	if tb_name != list_type and search_type != 5:	#5代表重置搜索，即不考虑搜索条件；tb_name用于检查当前的搜索参数是否与表格相对应
		if search_type == '0':
			g.kw['number'] = number
		if search_type == '1' or search_type == '4':
			g.kw['submitter_type'] = submitter
		if search_type == '2' or search_type == '4':
			result = result.filter(Advice.area.like('%'+area+'%'))
		if search_type == '3' or search_type == '4':
			result = result.filter(Advice.submission_date.between(start, end))
	if list_type == 'valid':
		result = result.filter(or_(Advice.state==1, Advice.state==2))
	elif list_type == 'finish':
		result = result.filter(or_(Advice.state==3, Advice.state==4))
	else:
		return jsonify({'state': 1, 'msg': u'参数错误'})
	result = result.filter_by(**g.kw).order_by(db.desc(Advice.submission_date)).paginate(offset/limit+1, limit, False)
	count = result.total
	data = []
	for item in result.items:
		data.append({
			'number': item.number,
			'type': u'建议' if item.type else u'投诉',
			'content': item.content,
			'name': item.name,
			'phone': item.phone,
			'time': item.finish_date.strftime("%Y-%m-%d %H:%M:%S") if list_type == 'finish' else item.submission_date.strftime("%Y-%m-%d %H:%M:%S"),
			'area': item.area,
			'operate': '?number=%s' % item.number
		})
	json = {'total': count, 'rows': data}
	return jsonify(json)


@advice.route('/details/')
def details():	#投诉建议详情
	number = request.values.get('number')
	if number is None:
		return render_template('404.html'), 404
	g.kw['number'] = number
	result = Advice.query.filter_by(**g.kw).first()
	if result:
		records = Tracking.query.filter_by(aid=result.id, application_type='advice').order_by(Tracking.time.desc()).all()	#获取跟进记录
		return render_template('tracking/advice/detail.html', data=result, records=records)
	return render_template('404.html'), 404	


@advice.route('/handle/', methods=['GET', 'POST'])
def handled():	#置为已处理状态
	app_number = request.values.get('app_number')
	if app_number is None:
		return jsonify({'state': -1, 'msg': u'参数不足'})
	g.kw['number'] = app_number
	result = Advice.query.filter_by(**g.kw).filter(or_(Advice.state==1, Advice.state==2)).first()
	if result:
		result.state = 3
		result.finish_date = datetime.datetime.now()
		result.save()
		log(u'将投诉建议%s置为已处理' % result.number)
		return jsonify({'state': 0})
	return jsonify({'state': 2})

@advice.route('/add_tracking/', methods=['GET', 'POST'])
def add_tracking():	#添加跟进记录
	app_number = request.values.get('app_number')
	content = request.values.get('content')
	if app_number is None or content is None:
		return jsonify({'state': -1, 'msg': u'参数不足'})
	if content == "":
		return jsonify({'state': -1, 'msg': u'请填写跟进内容'})
	g.kw['number'] = app_number
	result = Advice.query.filter_by(**g.kw).filter(or_(Advice.state==0, Advice.state==1)).first()
	if not result:
		return jsonify({'state': 2, 'msg': u'对象不存在'})
	record = Tracking(application_type='advice', aid=result.id, tracker_id=session.get('sid'), tracker_name=session.get('name'), content=safe_data(content), time=datetime.datetime.now())
	record.save()
	if result.state == 0:
		result.state = 1
		result.save()
		log(u'为投诉建议%s添加跟进记录' % result.number)
	return jsonify({'state': 0})

